package com.buydeem.share.springtxpropagation.service.impl;

import com.buydeem.share.springtxpropagation.dao.BookMapper;
import com.buydeem.share.springtxpropagation.model.Book;
import com.buydeem.share.springtxpropagation.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zengchao
 * @version 1.0.0
 * @ClassName BookServiceImpl.java
 * @Description TODO
 * @createTime 2021年06月21日 20:03:00
 */
@Service
@Slf4j
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

    /**
     * 如果已经存在事务则加入该事务，如果不存在，则新建一个新的事务
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void insertBook1() {
        log.info("插入insertBook1");
        Book book = new Book("insertBook1");
        bookMapper.insertBook(book);
        log.info("插入insertBook1完成");
    }

    /**
     * 如果存在事务则加入，不存在则已非事务的方式运行
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public void insertBook2() {
        log.info("插入insertBook2");
        Book book = new Book("insertBook2");
        bookMapper.insertBook(book);
        log.info("插入insertBook2完成");
    }

    /**
     * 如果存在事务则加入，不存在直接抛出异常
     */
    @Override
    @Transactional(propagation = Propagation.MANDATORY)
    public void insertBook3() {
        log.info("插入insertBook3");
        Book book = new Book("insertBook3");
        bookMapper.insertBook(book);
        log.info("插入insertBook3完成");
    }

    /**
     * 如果存在事务，则挂起当前事务，然后新建事务
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void insertBook4() {
        log.info("插入insertBook4");
        Book book = new Book("insertBook4");
        bookMapper.insertBook(book);
        log.info("插入insertBook4完成");
    }

    /**
     * 如果存在事务，则挂起当前事务，以非事务形式运行
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void insertBook5() {
        log.info("插入insertBook5");
        Book book = new Book("insertBook5");
        bookMapper.insertBook(book);
        log.info("插入insertBook5完成");
    }

    /**
     * 如果不存在事务，则已非事务形式运行。如果存在事务，则抛出异常
     */
    @Override
    @Transactional(propagation = Propagation.NEVER)
    public void insertBook6() {
        log.info("插入insertBook6");
        Book book = new Book("insertBook6");
        bookMapper.insertBook(book);
        log.info("插入insertBook6完成");
    }

    /**
     *
     */
    @Override
    @Transactional(propagation = Propagation.NESTED)
    public void insertBook7() {
        log.info("插入insertBook7");
        Book book = new Book("insertBook7");
        bookMapper.insertBook(book);
        log.info("插入insertBook7完成");
    }
}
